package com.ztw.yygh.msm.controller;

import com.aliyuncs.utils.StringUtils;
import com.ztw.yygh.common.result.Result;
import com.ztw.yygh.msm.service.MsmService;
import com.ztw.yygh.msm.utils.RandomUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.Random;
import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("/api/msm")
public class MsmApiController {
    @Resource
    private MsmService msmService;

    @Resource
    private RedisTemplate<String,String> redisTemplate;

    //发送手机验证码
    @GetMapping("send/{phone}")
    public Result sendCode(@PathVariable String phone){
        //从redis 获取验证码 能获取到则返回ok
        //key->phone value->验证码
        String code= redisTemplate.opsForValue().get(phone);
        if(!StringUtils.isEmpty(code)){
            return Result.ok();
        }
        //不能获取到则生成验证码，通过整合短信验证服务进行发送
        code= RandomUtil.getFourBitRandom();
        //阿里云短信服务
        boolean isSend=msmService.send(phone,code);
        //有效时间
        if(isSend){
            redisTemplate.opsForValue().set(phone, code, 5, TimeUnit.MINUTES);
            return Result.ok();
        }else{
            return Result.fail().message("发送短信失败");
        }
    }
}
